package com.archermind.common;
import java.sql.*;
/*
 * 数据库链接类
 */
public class DBCommon 
{
     static DBCommon dbCommon = null;
     Connection conn = null;
     PreparedStatement ps =  null;
     ResultSet rs = null;
     String mySqlDriver = "com.mysql.jdbc.Driver";
     String mySqlUrl = "jdbc:mysql://10.11.18.148:3306/tcldatabase";
     //String mySqlUrl = "jdbc:mysql://127.0.0.1:3306/test";
     String mysqlUsername ="root";
     String mysqlPassword ="root";
     
     public DBCommon()
     {
    	 
     }
     
     public static  DBCommon getInstance()
     {
    	 if(dbCommon == null)
    	 {
    		 dbCommon = new DBCommon();
    	 }
    	 
    	 return dbCommon;
     }
     
     public Connection getConnection()
     {
    	 try
    	 {
    		 Class.forName(mySqlDriver);
    		 conn = DriverManager.getConnection(mySqlUrl,mysqlUsername,mysqlPassword);
    	 }
    	 catch(Exception e)
    	 {
    		 System.out.println("数据库连接异常");
    		 e.printStackTrace();
    	 }
    	 return conn;
     }
     
     public ResultSet executeSearch(String sql,String  args[],String...  flag)
     {
    	 try
    	 {
    	 	 ps = this.getConnection().prepareStatement(sql); 
    	 	 if (args!=null)
    	 	 {
    	 		for(int i =0;i< args.length;i++)
    	 		{
           				ps.setString(i+1, args[i]);
    	 		}
			}
    	   	
    	   	if( flag != null  &&  flag.length>0 )
    	   	{    
    	   		 for(int i =0;i< args.length;i++)
	           	 {
	           			ps.setString(args.length+1+i, args[i]);           			
	           	 }
	    	   	  for(int i =0;i< args.length;i++)
	             {
	              			ps.setString(args.length*2+1+i, args[i]);           			
	              }
    	   		
    	   	}
    		rs = ps.executeQuery();

    	 }
    	 catch(Exception e)
    	 {
     		 System.out.println("数据库查询异常");
    		 e.printStackTrace();
    	 }       	
 		return rs;
     }
     
     public int updateTable(String sql,String  args[])
     {
    	 int ret=0;
    	 try
    	 {
    	 	 ps = this.getConnection().prepareStatement(sql);  		
    	   	for(int i =0;i< args.length;i++)
        	 {
        			ps.setString(i+1, args[i]);
        	 }
    	   	
    		ret = ps.executeUpdate();

    	 }
    	 catch(Exception e)
    	 {
     		 System.out.println("数据库查询异常");
    		 e.printStackTrace();
    	 }       	
 		return ret;
     }
     
     public void close()
     {
    	 try
    	 {
		    	 if (rs!= null)
		    	 {
		    		 rs.close();
		    	 }
		    	 if(ps != null)
		    	 {
		    		 ps.close();
		    	 }
		    	 if(conn != null)
		    	 {
		    		 conn.close();
		    	 }
    	 }
    	 catch(Exception e)
    	 {
    		   System.out.println("数据库连接异常");
    		 	e.printStackTrace();
    	 }
     }
}
